package com.hdl.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdl.JSONSerializer;
import com.hdl.RpcDecode;
import com.hdl.RpcEncoder;
import com.hdl.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {
    private static ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static UserClientHandler client;

    /*** 创建一个代理对象 */

    public static Object createProxy(final Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, (proxy, method, args) -> {
            if (client == null) {
                initClient();
            }
            final RpcRequest rpcRequest = new RpcRequest();
            rpcRequest.setClassName(serviceClass.getName());
            rpcRequest.setClazz(serviceClass);
            // 设置参数
            rpcRequest.setParameters(args);
            rpcRequest.setMethodName(method.getName());
            rpcRequest.setRequestId(UUID.randomUUID().toString().replaceAll("-", ""));

            // 设置参数类型
            if (args.length > 0) {
                Class<?>[] paramsTypes = new Class[args.length];
                for (int i = 0; i < args.length; i++) {
                    Class<?> aClass = args[i].getClass();
                    paramsTypes[i] = aClass;
                }
                rpcRequest.setParameterTypes(paramsTypes);
            }
            client.setPara(rpcRequest);
            return executor.submit(client).get();
        });
    }

    /*** 初始化客户端 */
    private static void initClient() {
        client = new UserClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        p.addLast(new StringDecoder());
                        p.addLast(client);
                    }
                });
        try {
            b.connect("localhost", 8990).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}